/*
 * 描述
 * Created by: litangyu
 * 包含类名列表
 * 版本信息，版本号 v1.0
 * 创建日期 16/8/30
 * 版权声明
*/
package com.foton.logistic.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.foton.logistic.R;
import com.foton.logistic.activity.OrderDetailActivity;
import com.foton.logistic.activity.UploadAbnormalActivity;
import com.foton.logistic.activity.UploadImageActivity;
import com.foton.logistic.adapter.OrderListAdapter;
import com.foton.logistic.base.BaseApplication;
import com.foton.logistic.base.BaseFragment;
import com.foton.logistic.daemon.IntentWrapper;
import com.foton.logistic.listener.IOnOrderClickListener;
import com.foton.logistic.listener.IOnRefreshListener;
import com.foton.logistic.listener.IOnResultListener;
import com.foton.logistic.listener.IOnTryClickListener;
import com.foton.logistic.model.GPSEntity;
import com.foton.logistic.model.order.LocalOrderEntity;
import com.foton.logistic.model.order.LocationEntity;
import com.foton.logistic.model.order.OrderEntity;
import com.foton.logistic.model.order.OrderListResult;
import com.foton.logistic.service.LocationService;
import com.foton.logistic.task.DispatchTask;
import com.foton.logistic.task.ShowDialogTask;
import com.foton.logistic.task.ShowLoadTask;
import com.foton.logistic.task.TaskConstant;
import com.foton.logistic.util.BaseConstant;
import com.foton.logistic.util.BroadcastUtil;
import com.foton.logistic.util.LocationUtil;
import com.foton.logistic.util.OptionUtil;
import com.foton.logistic.util.OrderUtil;
import com.foton.logistic.util.SharedUtil;
import com.foton.logistic.util.TimeUtil;
import com.foton.logistic.util.net.HttpUtil;
import com.foton.logistic.util.tool.DataCleanManager;
import com.foton.logistic.util.tool.FileUtil;
import com.foton.logistic.util.tool.LogUtil;
import com.foton.logistic.util.tool.StringUtil;
import com.foton.logistic.view.ultimate.UltimateRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * 描述
 * 订单列表
 * Created by: litangyu<br/>
 * Created on: 16/8/30 下午1:29
 */
public class OrderListFragment extends BaseFragment {
    private View rootView;
    @InjectView(R.id.ft_fragment_order_list_rv)
    public UltimateRecyclerView ultimateRecyclerView;
    @InjectView(R.id.base_ui_title_open_loc_per)
    TextView locSetText;
    private OrderListAdapter mAdapter;
    List<OrderEntity> operateList = new ArrayList<OrderEntity>();
    List<OrderEntity> normalList = new ArrayList<OrderEntity>();
    Map<String,List<OrderEntity>> mergeMap = new HashMap<String,List<OrderEntity>>();
    private final static String TYPE_GET_ALL = "0";
    private int pageNumber = BaseConstant.PAGER_START;
    List<OrderEntity> resultList;

    public static boolean isForeground = false;

    public static OrderListFragment self;
    private boolean hasLocation = true;
    private ReceiveBroadcast receiveBroadcast;
    LocationService locationService;
    private LocalOrderEntity localOrderEntity;
    private double distance=50000;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
    Bundle savedInstanceState) {
        setTaskTag(getClass().getSimpleName());
        if (null == rootView) {
            rootView = inflater.inflate(R.layout.ft_fragment_order_list, null);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout
                    .LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            rootView.setLayoutParams(params);
            ButterKnife.inject(this, rootView);
            init();
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
    }

    @Override
    public void init() {
        setTitleTextVisibility(View.VISIBLE);
        setTitleText(getString(R.string.my_order));
        locSetText.setVisibility(View.VISIBLE);
        initRecyclerView();
        registerBroadcast();
        locationService = LocationService.getInstance(getActivity());
        refresh(true);
//        isPrepared = true;
//        lazyLoad();
        self = this;
       /* localOrderEntity = SharedUtil.getLocalOrderEntity(BaseApplication.self());
        GPSEntity gpsEntity = LocationUtil.gcj_To_Gps84(Double.parseDouble(SharedUtil.getLat(BaseApplication.self())), Double.parseDouble(SharedUtil.getLng(BaseApplication.self())));
        double wgLat = gpsEntity.getWgLat();
        double wgLon = gpsEntity.getWgLon();
        if (localOrderEntity!=null) {
            if (localOrderEntity.order!=null) {
                if(localOrderEntity.order.startPlace!=null) {
                    distance = DistanceUtil.getDistance(new LatLng(Double.parseDouble(localOrderEntity.order.startPlace.lat), Double.parseDouble(localOrderEntity.order.startPlace.lon)),
                            new LatLng(wgLat, wgLon));
                }
            }
        }
        LogUtil.e("++++++++++++++"+distance);*/
    }

    @Override
    public void onResume() {
        super.onResume();
        isForeground = true;
    }

    @Override
    public void onDestroy() {
        try {
            getActivity().unregisterReceiver(receiveBroadcast);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

    private void initRecyclerView() {
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        ultimateRecyclerView.setLayoutManager(manager);
        ultimateRecyclerView.setHasFixedSize(true);
        ultimateRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mAdapter = new OrderListAdapter(getActivity(), operateList);
        mAdapter.setiOnOrderClickListener(new IOnOrderClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(getActivity(), OrderDetailActivity.class);
                intent.putExtra(BaseConstant.INTENT_ID, operateList.get(position).id);
                intent.putExtra(BaseConstant.INTENT_CONTENT, operateList.get(position));
                List<OrderEntity> schedOrderList = mergeMap.get(operateList.get(position).schedId);
                OrderListResult orderListResult = new OrderListResult();
                orderListResult.saveMergeList(schedOrderList);
                intent.putExtra(BaseConstant.INTENT_ARG,orderListResult);
                startActivity(intent);
            }

            @Override
            public void onExceptionClick(int position) {
                Bundle bundle = new Bundle();
                bundle.putString(BaseConstant.INTENT_ID, operateList.get(position).id);
                bundle.putInt(BaseConstant.INTENT_ST, operateList.get(position).status);
                Intent intent = new Intent(getActivity(), UploadAbnormalActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }

            @Override
            public void onOptClick(int position) {
                GPSEntity gpsEntity = LocationUtil.gcj_To_Gps84(Double.parseDouble(SharedUtil.getLat(BaseApplication.self())), Double.parseDouble(SharedUtil.getLng(BaseApplication.self())));
                double wgLat = gpsEntity.getWgLat();
                double wgLon = gpsEntity.getWgLon();
                distance = DistanceUtil.getDistance(new LatLng(Double.parseDouble(operateList.get(position).startPlace.lat), Double.parseDouble(operateList.get(position).startPlace.lon)),
                        new LatLng(wgLat, wgLon));
                Bundle bundle;
                Intent intent;
                int status = operateList.get(position).realStatus;
                switch (status) {
                    case OptionUtil.ORDER_STATUS_1:
                        //接单
                        if (hasLocation) {

                            if (distance>50000){
                                Toast.makeText(BaseApplication.self(), "接单距离起运点不得超过50公里", Toast
                                        .LENGTH_LONG).show();
                                return;
                            }
                            orderReceive(true, operateList.get(position));
                        } else {
                            Toast.makeText(BaseApplication.self(), getString(R.string.loc), Toast
                                    .LENGTH_LONG).show();
                        }
                        break;
                    case OptionUtil.ORDER_STATUS_2:
                        //出发签到
                        if (hasLocation) {
                            signForOrder(true, 0, operateList.get(position));
                        } else {
                            BaseApplication.self().location(BaseApplication.LOCTIME);
                            OptionUtil.addToast(BaseApplication.self(), getString(R.string.loc));
                        }
                        break;
                    case OptionUtil.ORDER_STATUS_20:
                        //跳转到出发拍照
                        bundle = new Bundle();
                        bundle.putString(BaseConstant.INTENT_ID, operateList.get(position).id);
                        bundle.putInt(BaseConstant.INTENT_TYPE, BaseConstant
                                .UPLOAD_IMAGE_TYPE_START);
                        intent = new Intent(getActivity(), UploadImageActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                        break;
                    case OptionUtil.ORDER_STATUS_3:
                        //到达签到
                        uploadTrack(true, operateList.get(position));
                        break;
                    case OptionUtil.ORDER_STATUS_30:
                        //跳转到到达拍照
                        bundle = new Bundle();
                        bundle.putString(BaseConstant.INTENT_ID, operateList.get(position).id);
                        bundle.putInt(BaseConstant.INTENT_TYPE, BaseConstant
                                .UPLOAD_IMAGE_TYPE_ARRIVE);
                        intent = new Intent(getActivity(), UploadImageActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                        break;
                    case OptionUtil.ORDER_STATUS_4:
                        //到达签到
                        uploadTrack(true, operateList.get(position));
                        break;
                    case OptionUtil.ORDER_STATUS_41:
                        //跳转到到达拍照
                        bundle = new Bundle();
                        bundle.putString(BaseConstant.INTENT_ID, operateList.get(position).id);
                        bundle.putInt(BaseConstant.INTENT_TYPE, BaseConstant
                                .UPLOAD_IMAGE_TYPE_ARRIVE);
                        intent = new Intent(getActivity(), UploadImageActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                        break;
                }
            }

            @Override
            public void onRecordClick(int position) {
//                if (BaseConstant.IS_KEEP_LIVE){
//                    IntentWrapper.whiteListMatters(getActivity(), "轨迹跟踪服务的持续运行");
//                }
                LocalOrderEntity localOrderData = OrderUtil.getLocalOrder(getActivity(), operateList.get(position));
                if (localOrderData==null){
                    OrderUtil.startLocation(getActivity(),titleText,operateList.get(position),mergeMap.get(operateList.get(position).schedId));
                }else {
                    int res = BaseApplication.self().location(BaseApplication.LOCTIME);
                    if (res==0){
                        //启动定位成功
                        OptionUtil.addToast(getActivity(), getString(R.string.track_bd_loc_success));
                    }else {
                        OptionUtil.addToast(getActivity(), getString(R.string.track_bd_loc_fail));
                    }
                }
            }

            @Override
            public void onRejClick(int position) {
                orderRej(true, operateList.get(position));
            }
        });
        ultimateRecyclerView.setAdapter(mAdapter);
        ultimateRecyclerView.enableLoadmore(true);
        ultimateRecyclerView.enableSwipeRefresh(true);
        ultimateRecyclerView.endFinish(false);
        ultimateRecyclerView.setOnRefreshListener(new IOnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh(false);
            }

            @Override
            public void onLoadMore() {
                getRepairList(false);
            }
        });

    }

    @OnClick(R.id.base_ui_title_open_loc_per)
    public void locSetting(View view){
        if (BaseConstant.IS_KEEP_LIVE){
            IntentWrapper.whiteListMatters(getActivity(), "轨迹跟踪服务的持续运行");
        }
        OptionUtil.setting(getActivity());
    }

    @Override
    protected void lazyLoad() {

    }

    private void updateInfo(ShowLoadTask task) {
        if (resultList != null) {
            if (pageNumber == BaseConstant.PAGER_START) {
                normalList.clear();
            }
            pageNumber++;
            for (OrderEntity dataEntity : resultList) {
                normalList.add(dataEntity);
            }
            if (resultList.size() < BaseConstant.PAGER_COUNT) {
                ultimateRecyclerView.endFinish(true);
            } else {
                ultimateRecyclerView.endFinish(false);
            }
            if (normalList.size() == 0 && task != null) {
                task.addEmptyView("", "", R.mipmap.base_view_link_error);
            }
            LogUtil.e("normalList.size()= "+normalList.size());
            mergeOrderBySchedId();
            LogUtil.e("operateList.size()= "+operateList.size());
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 根据SchedId和终点地址，合并订单
     */
    private void mergeOrderBySchedId(){
        List<OrderEntity> orderList = new ArrayList<OrderEntity>();
        operateList.clear();
        if (normalList !=null&& normalList.size()>0){
            for(int i=0;i< normalList.size();i++){
                if (i==0){
                    orderList.clear();
                    orderList.add(normalList.get(i));
                    if (normalList.size()==1){
                        operateList.add(orderList.get(0));
                    }
                }else {
                    if (normalList.get(i-1).schedId.equals(normalList.get(i).schedId)){
                        orderList.add(normalList.get(i));
                        if (i==(normalList.size()-1)){
                            //处理批量调度的订单，按终点地址合并
                            if (orderList.size()>1){
                                //多单处理
                                int beforeIndex = operateList.size();
                                mergeOrderByEndPlace(orderList);
                                int afterIndex = operateList.size();
                                //将批量调度的订单赋予对应订单
                                List<OrderEntity> schedOrderList = new ArrayList<OrderEntity>();
                                for (int index=beforeIndex;index<afterIndex;index++){
                                    schedOrderList.add(operateList.get(index));
                                }
                                //TODO
                                mergeMap.put(schedOrderList.get(0).schedId,schedOrderList);
//                            for (int index=beforeIndex;index<afterIndex;index++){
//                                operateList.get(index).schedOrderList = schedOrderList;
//                            }
                            }else {
                                //单个订单不需处理
                                operateList.add(orderList.get(0));
                            }
                        }
                    }else {
                        //处理批量调度的订单，按终点地址合并
                        if (orderList.size()>1){
                            //多单处理
                            int beforeIndex = operateList.size();
                            mergeOrderByEndPlace(orderList);
                            int afterIndex = operateList.size();
                            //将批量调度的订单赋予对应订单
                            List<OrderEntity> schedOrderList = new ArrayList<OrderEntity>();
                            for (int index=beforeIndex;index<afterIndex;index++){
                                schedOrderList.add(operateList.get(index));
                            }
                            //TODO
                            mergeMap.put(schedOrderList.get(0).schedId,schedOrderList);
//                            for (int index=beforeIndex;index<afterIndex;index++){
//                                operateList.get(index).schedOrderList = schedOrderList;
//                            }
                        }else {
                            //单个订单不需处理
                            operateList.add(orderList.get(0));
                        }
                        if (i==(normalList.size()-1)){
                            operateList.add(normalList.get(i));
                        }else {
                            orderList.clear();
                            orderList.add(normalList.get(i));
                        }

                    }
                }
            }
//            OrderUtil.saveOrderList(getContext(),operateList);
        }
    }

    /**
     * 根据终点地址，合并订单  递归调用
     * @param orderList
     */
    private void mergeOrderByEndPlace(List<OrderEntity> orderList){
        OrderEntity orderEntity = orderList.get(0);
        orderEntity.mergeOrderNum = orderEntity.orderNum;
        orderEntity.mergeOrderCnt = 1;
        orderList.remove(0);
        List<OrderEntity> leftOrderList = new ArrayList<OrderEntity>();

        for (int o=0;o<orderList.size();o++) {
            if (orderEntity!=null) {
                if (orderEntity.endPlace!=null) {
                    if (orderEntity.endPlace.lat!=null&&orderEntity.endPlace.lon!=null){
                    if (orderEntity.endPlace.lat.equals(orderList.get(o).endPlace.lat) && orderEntity.endPlace.lon.equals(orderList.get(o).endPlace.lon)) {
                        //相同终点，合并到第一个订单中
                        orderEntity.mergeOrderNum += "," + orderList.get(o).orderNum;
                        orderEntity.mergeOrderCnt++;
                    } else {
                        leftOrderList.add(orderList.get(o));
                       }
                    }
                }

            }
        }
        operateList.add(orderEntity);
        if (leftOrderList.size()>0){
            mergeOrderByEndPlace(leftOrderList);
        }

    }

    public void refresh(boolean showLoad) {
        pageNumber = BaseConstant.PAGER_START;
        getRepairList(showLoad);
    }

    private void getRepairList(final boolean showLoad) {
        Map<String, Object> argMap = HttpUtil.getEncryMap(getActivity());
        argMap.put("pageNumber", String.valueOf(pageNumber));
        argMap.put("pageSize", String.valueOf(BaseConstant.PAGER_COUNT));
        argMap.put("type", TYPE_GET_ALL);

        ShowLoadTask task = new ShowLoadTask(getActivity(), taskTag, containLayout, loadLayout,
                getString(R.string.task2), showLoad, retryListener, BaseConstant.GET_ORDER_LIST,
                argMap, TaskConstant.POST);
        task.setParseClass(OrderListResult.class);
        task.setiOnResultListener(new IOnResultListener() {
            @Override
            public void onOK(DispatchTask task) {
                if (task.resultEntity instanceof OrderListResult) {
                    OrderListResult res = (OrderListResult) task.resultEntity;
                    resultList = res.data;
                    updateInfo((ShowLoadTask) task);
                }
            }

            @Override
            public void onError(DispatchTask task) {

            }

            @Override
            public void onDone(DispatchTask task) {
                try {
                    ultimateRecyclerView.refreshFinish();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        task.execute();
    }

    IOnTryClickListener retryListener = new IOnTryClickListener() {
        @Override
        public void onTry() {
            refresh(true);
        }

        @Override
        public void onOption() {

        }
    };

    /**
     * 接单
     *
     * @param showDialog
     */
    private void orderReceive(boolean showDialog,final OrderEntity orderData) {
        final Map<String, Object> argMap = HttpUtil.getEncryMap(BaseApplication.self());
        argMap.put("tel", SharedUtil.getTel(BaseApplication.self()));
        argMap.put("orderId", orderData.id);
        argMap.put("lat", SharedUtil.getLat(BaseApplication.self()));
        argMap.put("lon", SharedUtil.getLng(BaseApplication.self()));
        argMap.put("address", SharedUtil.getAddress(BaseApplication.self()));

        //TODO 判断50公里提示

        ShowDialogTask task = new ShowDialogTask(BaseApplication.self(), taskTag, titleText, getString(R.string
                .task3), showDialog, BaseConstant.ORDER_RECEIVE, argMap, TaskConstant.POST);
        task.setiOnResultListener(new IOnResultListener() {
            @Override
            public void onOK(DispatchTask task) {
                OptionUtil.addToast(BaseApplication.self(), getString(R.string.tip24));
                try {
                    if (BaseConstant.LOGING)
                        FileUtil.writeFile(BaseConstant.LOGPATH, "\n时间："+ TimeUtil.getCurrentTime("yyyy-MM-dd HH:mm:ss")+" 接单提交记录成功：经度=" +argMap.get("lon")+" 纬度=" +argMap.get("lat")+" orderId=" +argMap.get("orderId"), true);
                }catch (Exception e){
                    e.printStackTrace();
                }
                BroadcastUtil.sendOrderRefreshBroadcast(BaseApplication.self());
                refresh(true);
            }

            @Override
            public void onError(DispatchTask task) {

            }

            @Override
            public void onDone(DispatchTask task) {

            }
        });
        task.execute();
    }
    /**
     * 撤销接单
     *
     * @param showDialog
     */
    private void orderRej(boolean showDialog,final OrderEntity orderData) {
        final Map<String, Object> argMap = HttpUtil.getEncryMap(BaseApplication.self());
        //argMap.put("tel", SharedUtil.getTel(BaseApplication.self()));
        argMap.put("orderId", orderData.id);
        argMap.put("lat", SharedUtil.getLat(BaseApplication.self()));
        argMap.put("lon", SharedUtil.getLng(BaseApplication.self()));
        argMap.put("address", SharedUtil.getAddress(BaseApplication.self()));

        //TODO 判断50公里提示

        ShowDialogTask task = new ShowDialogTask(BaseApplication.self(), taskTag, titleText, getString(R.string
                .task3), showDialog, BaseConstant.ORDER_REJECT, argMap, TaskConstant.POST);
        task.setiOnResultListener(new IOnResultListener() {
            @Override
            public void onOK(DispatchTask task) {
                OptionUtil.addToast(BaseApplication.self(), getString(R.string.tip25));
                try {
                    /*if (BaseConstant.LOGING)
                        FileUtil.writeFile(BaseConstant.LOGPATH, "\n时间："+ TimeUtil.getCurrentTime("yyyy-MM-dd HH:mm:ss")+" 撤销成功：经度=" +argMap.get("lon")+" 纬度=" +argMap.get("lat")+" orderId=" +argMap.get("orderId"), true);*/
                }catch (Exception e){
                    e.printStackTrace();
                }
                BroadcastUtil.sendOrderRefreshBroadcast(BaseApplication.self());
                refresh(true);
            }

            @Override
            public void onError(DispatchTask task) {

            }

            @Override
            public void onDone(DispatchTask task) {

            }
        });
        task.execute();
    }

    /**
     * 签到
     *
     * @param showDialog
     * @param type       类型：0是出发、1是到达
     */
    private void signForOrder(boolean showDialog, final int type,final OrderEntity orderData) {
        final LocalOrderEntity localOrderEntity = OrderUtil.getLocalOrder(getActivity(), orderData);
        final Map<String, Object> argMap = HttpUtil.getEncryMap(getActivity());
        argMap.put("tel", SharedUtil.getTel(getActivity()));
        argMap.put("orderId", orderData.id);
        if (type == 0) {
            argMap.put("type", "1");
            argMap.put("lat", SharedUtil.getLat(getActivity()));
            argMap.put("lon", SharedUtil.getLng(getActivity()));
           /* argMap.put("lat", localOrderEntity.order.endPlace.lat);
            argMap.put("lon", localOrderEntity.order.endPlace.lon);*/
            argMap.put("address", SharedUtil.getAddress(getActivity()));
        } else {
            argMap.put("type", "4");
            argMap.put("auto", "0");

            //TODO 多个订单批量调度的可能存在问题--待运行反馈
            OrderEntity order = null;
            if (localOrderEntity!=null){
                if (localOrderEntity.schedOrderList!=null){
                    for (OrderEntity orderEntity:localOrderEntity.schedOrderList){
                        if (orderEntity.id.equals(orderData.id)){
                            order = orderEntity;
                        }
                    }
                }else {
                    order = localOrderEntity.order;
                }
            }

//            if ((order!=null&&order.isArrivedAndOut)||orderData.status==OptionUtil.ORDER_STATUS_4){
//                //到终点圈然后出圈 采用目标地址的经纬度116.401578,39.903973
//                //平台设为已到达后，app可以到达签到，采用目标地址的经纬度116.40143,39.904309
////                LogUtil.e("localOrderData.isArrivedAndOut="+localOrderData.isArrivedAndOut);
//                if (orderData.endPlace!=null&&StringUtil.isEmpty(orderData.endPlace.lat)){
//                    OptionUtil.addToast(getActivity(),"终点坐标缺失");
//                    return;
//                }
//                double lat = Double.parseDouble(orderData.endPlace.lat)+0.001;
//                double lng = Double.parseDouble(orderData.endPlace.lon)+0.001;
//                String strLat = String.valueOf(lat);
//                String strLon = String.valueOf(lng);
//                if (strLat.length()>13){
//                    strLat = strLat.substring(0,13);
//                }
//                if (strLon.length()>13){
//                    strLon = strLon.substring(0,13);
//                }
//                argMap.put("lat", ""+strLat);
//                argMap.put("lon", ""+strLon);
//                if (orderData.endPlace!=null)
//                    argMap.put("address", ""+orderData.endPlace.address);
//            }else {
                //到达签到采用轨迹最后一个点
                List<LocationEntity> locationEntityList = locationService.queryByOrderId(orderData.schedId,false);
                if (locationEntityList!=null&&locationEntityList.size()>0){
                    long ct = System.currentTimeMillis();
                    long lt = Long.parseLong(locationEntityList.get(0).getCreate_time());

                   /* if ((ct-lt)>600000){
                        OptionUtil.addToast(getActivity(),"最后定位点在10分钟之前，正在重新定位，预计需要1分钟");
                        return;
                    }*/

                    argMap.put("lat", locationEntityList.get(0).getLat());
                    argMap.put("lon", locationEntityList.get(0).getLng());
                    argMap.put("address", locationEntityList.get(0).getAddress());
                }else {
                    argMap.put("lat", ""+ SharedUtil.getLat(getActivity()));
                    argMap.put("lon", ""+ SharedUtil.getLng(getActivity()));
                    argMap.put("address", ""+ SharedUtil.getAddress(getActivity()));
                }
            }

//        }
        ShowDialogTask task = new ShowDialogTask(getActivity(), taskTag, titleText, getString(R.string
                .task3), showDialog, BaseConstant.ORDER_SIGN, argMap, TaskConstant.POST);
        task.setiOnResultListener(new IOnResultListener() {
            @Override
            public void onOK(DispatchTask task) {
                if (type == 0) {
                    OptionUtil.addToast(getActivity(), getString(R.string.tip12));
                    OrderUtil.startLocation(getActivity(),titleText,orderData,mergeMap.get(orderData.schedId));
                    if (BaseConstant.LOGING)
                        FileUtil.writeFile(BaseConstant.LOGPATH, "\n时间：" + TimeUtil.getCurrentTime("yyyy-MM-dd HH:mm:ss") + " 提货签到提交记录成功：经度=" + argMap.get("lon") + " 纬度=" + argMap.get("lat") + " orderId=" + argMap.get("orderId"), true);
                } else {
                    try {
                        BaseApplication.self().dealArrivedSign(orderData);
                        /*if (localOrderEntity!=null){
                            if (localOrderEntity.schedOrderList==null){
                                if (localOrderEntity.order.id.equals(orderData.id)){
                                    BaseApplication.self().stopOut(false);
                                }
                            }else {
                                if (localOrderEntity.schedOrderList.size()<=1){
                                    if (localOrderEntity.order.schedId.equals(orderData.schedId)){
                                        BaseApplication.self().stopOut(false);
                                    }
                                }else {
                                    boolean canStop = true;
                                    for (OrderEntity orderEntity:localOrderEntity.schedOrderList){
                                        if (orderData.id.equals(orderEntity.id)){
                                            orderEntity.isArrivedSign = true;
                                        }else {
                                            if (orderEntity.signEnd!=null&&!StringUtil.isEmpty(orderEntity.signEnd.operateTime)){

                                            }else {
                                                if (!orderEntity.isArrivedSign){
                                                    canStop = false;
                                                }
                                            }
                                        }
                                    }
                                    SharedUtil.saveLocalOrder(getContext(),localOrderEntity);
                                    if (canStop){
                                        BaseApplication.self().stopOut(false);
                                    }
                                }
                            }
                        }*/
                        if (BaseConstant.LOGING)
                            FileUtil.writeFile(BaseConstant.LOGPATH, "\n时间："+ TimeUtil.getCurrentTime("yyyy-MM-dd HH:mm:ss")+" 手动到达签到提交记录成功：经度=" +argMap.get("lon")+" 纬度=" +argMap.get("lat")+" orderId=" +argMap.get("orderId"), true);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                //清空临时图片
                DataCleanManager.cleanCustomCache(getActivity(), BaseConstant.IMAGETAMPPATH);
                refresh(true);
            }

            @Override
            public void onError(DispatchTask task) {

            }

            @Override
            public void onDone(DispatchTask task) {

            }
        });
        task.execute();
    }

    /**
     * 上传轨迹
     *
     * @param showDialog
     * @param orderEntity
     */
    private void uploadTrack(boolean showDialog,final OrderEntity orderEntity) {
        final List<LocationEntity> list = locationService.queryByOrderId(orderEntity.schedId);
        String latLng = "";//38.66545224,116.2541254, 2016-11-24 10:06:45,中国北京市海淀区丰秀中路
        for (LocationEntity locationEntity : list) {
            String item = locationEntity.lat + "," + locationEntity.lng + "," + TimeUtil
                    .formatServiceTime2(locationEntity.update_time) + "," + locationEntity.address;
            if (StringUtil.isEmpty(latLng)) {
                latLng = item;
            } else {
                latLng = latLng + "#" + item;
            }
            locationEntity.setIsUploaded("1");
        }
        if (StringUtil.isEmpty(latLng)) {
            SharedUtil.saveOrderTimer(getActivity(), System.currentTimeMillis());
            signForOrder(true, 1,orderEntity);
            return;
        }
        final Map<String, Object> argMap = HttpUtil.getEncryMap(getActivity());
        argMap.put("tel", SharedUtil.getTel(getActivity()));
        argMap.put("orderId", orderEntity.id);
        argMap.put("latLon", latLng);
        ShowDialogTask task = new ShowDialogTask(getActivity(), taskTag, titleText, getString(R.string
                .task3), showDialog, BaseConstant.UPLOAD_LATLNG, argMap, TaskConstant.POST);
        task.setShowTipSuccess(true);
        task.setiOnResultListener(new IOnResultListener() {
            @Override
            public void onOK(DispatchTask task) {
                locationService.update2Uploaded(list);
                SharedUtil.saveOrderTimer(getActivity(), System.currentTimeMillis());
                signForOrder(true, 1,orderEntity);
               /* try {
                    if (BaseConstant.LOGING)
                        FileUtil.writeFile(BaseConstant.LOGPATH, "\n时间："+ TimeUtil.getCurrentTime("yyyy-MM-dd HH:mm:ss")+" 轨迹上传成功："+argMap.get("latLon"), true);
                }catch (Exception e){
                    e.printStackTrace();
                }*/

            }

            @Override
            public void onError(DispatchTask task) {

            }

            @Override
            public void onDone(DispatchTask task) {

            }
        });
        task.execute();
    }

    private void registerBroadcast() {
        if (receiveBroadcast == null) {
            receiveBroadcast = new ReceiveBroadcast();
            IntentFilter filter = new IntentFilter();
            filter.addAction(BaseConstant.ACTION_ORDER_REFRESH);
            filter.addAction(BaseConstant.ACTION_LOCATION_LOC);
            getActivity().registerReceiver(receiveBroadcast, filter);
        }
    }

    public class ReceiveBroadcast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (action.equals(BaseConstant.ACTION_ORDER_REFRESH)) {
                    refresh(true);
                } else if (action.equals(BaseConstant.ACTION_LOCATION_LOC)) {
                    hasLocation = true;
                    int waitCnt = OrderUtil.getTrackWaitCount(getActivity());
                    mAdapter.updateTrackWaitCnt(waitCnt);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }



}
